package com.ams.common.web.config;

import feign.RequestInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author yuanss
 * @Date 2024/1/30 10:32
 * @Description: feign配置类
 * @Version 1.0
 */
@Configuration
public class FeignConfig {
    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 让DispatcherServlet向子线程传递RequestContext
     * @param servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean<DispatcherServlet> dispatcherRegistration(DispatcherServlet servlet){
        servlet.setThreadContextInheritable(true);
        return new ServletRegistrationBean<>(servlet,"/**");
    }

    @Bean
    public RequestInterceptor requestInterceptor(){
        return (requestTemplate) -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            //获取请求头
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String value = request.getHeader(name);
                    //将请求头添加到feign请求中
                    if (name.equalsIgnoreCase("serviceName")){
                        requestTemplate.header(name, value);
                    }
                }
            }
            requestTemplate.header("serviceName", applicationName);
        };
    }
}
